/**
 * @version 1.0.0.0
 * @copyright Copyright ©  2013
 * @compiler Bridge.NET 15.6.0
 */
Bridge.assembly("IPAExporter", function ($asm, globals) {
    "use strict";

    Bridge.define("App", {
        statics: {
            ctor: function () {
                App.userDataDir = require('path').join(require('electron').remote.app.getPath("userData"), "UserData");
                App.CheckAndCreateDir(App.userDataDir);

                App.MyAppPath = require('path').join(App.userDataDir, App.AppData, "myapp");
                App.ResignWorkDir = require('path').join(App.userDataDir, App.AppData, "resignwork");
                App.BatchWorkDir = require('path').join(App.userDataDir, App.AppData, "batchwork");
                App.ResignOutDir = require('path').join(App.userDataDir, App.AppData, "resignedipa");
                App.CerDir = require('path').join(App.userDataDir, "cerfile");
                App.AppPath = require('path').join(App.userDataDir, "app");
                App.LocaDataPath = require('path').join(App.userDataDir, App.AppData, "localdata");


                App.CheckAndCreateDir(require('path').join(App.userDataDir, App.AppData));
                App.CheckAndCreateDir(App.MyAppPath);
                App.CheckAndCreateDir(App.ResignWorkDir);
                App.CheckAndCreateDir(App.ResignOutDir);
                App.CheckAndCreateDir(App.BatchWorkDir);

                App.CheckAndCreateDir(App.CerDir);
                App.CheckAndCreateDir(App.LocaDataPath);

            },
            IsLogined: false,
            AppData: "AppData",
            MyAppPath: null,
            ResignOutDir: null,
            ResignWorkDir: null,
            BatchWorkDir: null,
            CerDir: null,
            AppPath: null,
            LocaDataPath: null,
            userDataDir: null,
            config: {
                events: {
                    OnLoginSuccess: null
                }
            },
            getSiteBaseUrl: function () {
                return window.SiteBaseUrl;
            },
            CheckAndCreateDir: function (dir) {
                if (!require('fs').existsSync(dir)) {
                    require('fs').mkdirSync(dir);
                }
            },
            TriggerLoginSuccess: function () {
                App.IsLogined = true;
                !Bridge.staticEquals(App.OnLoginSuccess, null) ? App.OnLoginSuccess() : null;
            }
        }
    });

    Bridge.define("IPAExporter.Pages.MainPage", {
        inherits: [Phone.RazorMobilePage],
        CurrentSelectedPath: "",
        pnlContent: null,
        lblSelectedFile: null,
        btnChooseFile: null,
        btnSubmit: null,
        lblExecuteCommand: null,
        lblExecuteError: null,
        ctor: function () {
            this.$initialize();
            Phone.RazorMobilePage.ctor.call(this);
            this.addOnPageInit(Bridge.fn.bind(this, this.MainPage_OnPageInit));
        },
        MainPage_OnPageInit: function () {
            this.btnChooseFile.click(Bridge.fn.bind(this, $asm.$.IPAExporter.Pages.MainPage.f2));

            this.btnSubmit.click(Bridge.fn.bind(this, $asm.$.IPAExporter.Pages.MainPage.f3));

        },
        Execute: function () {

            this.WriteLiteral("<div data-role=\"page\" class=\"mainPage\">\r\n    <div class=\"content\" id=\"pnlContent\">\r\n        <div class=\"form-horizontal\">\r\n            <div class=\"tipPanel\">\r\n                <div class=\"tipItem\">\r\n                    本工具可以将存档文件(.archive)导出为ipa文件。\r\n                </div>\r\n                <div class=\"tipItem\">\r\n                    在使用本工具之前，请先确保xcode已经使用了正确的证书进行编译生成项目。\r\n                </div>\r\n            </div>\r\n            <div class=\"contentPanel\">\r\n                <label class=\"chooseFile\">选择存档文件:</label>\r\n                <span id=\"lblSelectedFile\"></span>\r\n                <input type=\"button\" class=\"btn btn-primary\" id=\"btnChooseFile\" value=\"现在选择存档文件(.archive)...\" />\r\n                <button type=\"button\" class=\"btn btn-primary\" id=\"btnSubmit\" style=\"display:none; margin-left:30px\">立即导出为IPA文件</button>\r\n                <p id=\"lblExecuteCommand\">\r\n                </p>\r\n                <p id=\"lblExecuteError\"></p>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</div>");


        },
        InitialComponent: function () {
            this.pnlContent = this.pageObject.find("#pnlContent");
            this.lblSelectedFile = this.pageObject.find("#lblSelectedFile");
            this.btnChooseFile = this.pageObject.find("#btnChooseFile");
            this.btnSubmit = this.pageObject.find("#btnSubmit");
            this.lblExecuteCommand = this.pageObject.find("#lblExecuteCommand");
            this.lblExecuteError = this.pageObject.find("#lblExecuteError");
        }
    });

    Bridge.ns("IPAExporter.Pages.MainPage", $asm.$);

    Bridge.apply($asm.$.IPAExporter.Pages.MainPage, {
        f1: function (pathes) {
            this.CurrentSelectedPath = System.Linq.Enumerable.from(pathes).firstOrDefault(null, null);
            if (this.CurrentSelectedPath != null) {
                this.lblSelectedFile.text(this.CurrentSelectedPath);
            }
            JSLib.Extension.jQueryEx.SetVisible(this.btnSubmit, !System.String.isNullOrEmpty(this.CurrentSelectedPath));
        },
        f2: function (n) {
            require('electron').remote.dialog.showOpenDialog({ properties: ["openFile"], filters: [{ name: "存档文件", extensions: ["xcarchive"] }] }, Bridge.fn.bind(this, $asm.$.IPAExporter.Pages.MainPage.f1));
        },
        f3: function (n) {
            var $step = 0,
                $task1, 
                $taskResult1, 
                n, 
                $jumpFromFinally, 
                archivePath, 
                exportIPAPath, 
                exportPlistContent, 
                exportPlistFie, 
                result, 
                $asyncBody = Bridge.fn.bind(this, function () {
                    for (;;) {
                        $step = System.Array.min([0,1], $step);
                        switch ($step) {
                            case 0: {
                                archivePath = this.CurrentSelectedPath;
                                    if (System.String.isNullOrEmpty(archivePath)) {
                                        JSLib.Mobile.MessageBox.Alert("请先选择存档文件!");
                                        return;
                                    }

                                    exportIPAPath = require('path').join(archivePath, "../");

                                    exportPlistContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\r\n<plist version=\"1.0\">\r\n<dict>\r\n  <key>compileBitcode</key>\r\n  <false/>\r\n  <key>method</key>\r\n  <string>app-store</string>\r\n  <key>uploadBitcode</key>\r\n  <false/>\r\n  <key>uploadSymbols</key>\r\n  <false/>\r\n</dict>\r\n</plist>";
                                    exportPlistFie = require('path').join(App.userDataDir, App.AppData, "appStoreExportOption.plist");

                                    require('fs').writeFileSync(exportPlistFie, exportPlistContent, { encoding: "utf8" });
                                    $task1 = JSLib.ElectronEx.ProcessHelper.Run("xcodebuild", ["-exportArchive", System.String.format("-exportOptionsPlist", null), ObjExtension.WithEnclosingQuotation(exportPlistFie), "-archivePath", ObjExtension.WithEnclosingQuotation(archivePath), System.String.format("-exportPath", null), ObjExtension.WithEnclosingQuotation(exportIPAPath)], true, this);
                                    $step = 1;
                                    $task1.continueWith($asyncBody, true);
                                    return;
                            }
                            case 1: {
                                $taskResult1 = $task1.getAwaitedResult();
                                result = $taskResult1;
                                    if (result.ExitCode !== 0) {
                                        JSLib.Mobile.MessageBox.Alert("导出时失败!");
                                        this.lblExecuteCommand.text(System.String.format("执行命令: {0} ", result.Command));
                                        this.lblExecuteError.text(System.String.format("执行结果: {0}", result.ErrorMessage));
                                        return;
                                    } else {
                                        JSLib.Mobile.MessageBox.Alert("导出IPA文件成功!");
                                        require('electron').shell.showItemInFolder(exportIPAPath);
                                    }
                                return;
                            }
                            default: {
                                return;
                            }
                        }
                    }
                }, arguments);

            $asyncBody();
        }
    });

    Bridge.define("Program", {
        $main: function () {
            //Window.SetTimeout(async delegate
            //{
            //    var result = await ProcessHelper.Run("git", null);
            //    if (result.ExitCode != 0)
            //    {
            //        result.OutPutMessage.Dump();
            //    }
            //});
            //return;

            JSLib.Mobile.Application.IsBrowser = true;
            JSLib.Mobile.Application.EnableSystemLog = true;
            JSLib.Mobile.Application.AutoLoadCss = false;

            JSLib.Mobile.Application.setBaseNameSpace("Pages");
            JSLib.Mobile.Application.RootPath = "Pages/";

            JSLib.Mobile.PageResourceManager.MaxPageCount = 100;
            var mobilePageTypes = System.Linq.Enumerable.from(Bridge.Reflection.getAssemblyTypes($asm)).where($asm.$.Program.f1).toList(Function);
            JSLib.Mobile.MobilePage.Prepare(mobilePageTypes, true, "");
            JSLib.JSLibConfig.PageTransitionEffect = false;
            JSLib.Mobile.Application.DeviceType = JSLib.Mobile.DeviceType.Desktop;
            JSLib.Mobile.MobilePage.PageContainer = $(document.body);
            JSLib.Mobile.Application.PrepareApp();
            JSLib.Mobile.MobilePage.GotoPage$1(IPAExporter.Pages.MainPage);
        }
    });

    Bridge.ns("Program", $asm.$);

    Bridge.apply($asm.$.Program, {
        f1: function (n) {
            return Bridge.referenceEquals(Bridge.Reflection.getBaseType(n), Phone.RazorMobilePage);
        }
    });
});
